﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Exam.BLL;
using Exam.Model;
using System.Text;
namespace ExaminationWeb.Controllers
{
    public class SysMenuController : Controller
    {
        //
        // GET: /SysMenu/
        SysMenuService menuService = new SysMenuService();
        RoleMenuService rolemenuService = new RoleMenuService();
       [AllowAnonymous]
        public JsonResult GetMenuNode()
        {
            IQueryable<SysMenu> ISysMenu = menuService.LoadEntites(e => e.IsActive == 0);
            IQueryable<SysMenu> _ISysMenu = ISysMenu.Where(e => e.PMenuID == Guid.Empty).OrderBy(e=>e.Sort);
            builder.Append("[");
            GetNode(ISysMenu, _ISysMenu);
            builder.Append("]");
            return Json(builder.ToString(), JsonRequestBehavior.AllowGet);
        }
        List<Guid?> menulist = new List<Guid?>();
       [AllowAnonymous]
        public JsonResult GetMenuNodebyRole(string id)
        {
            menulist = rolemenuService.LoadEntites(e => e.RoleID == Guid.Parse(id)).Select(e => e.MenuID).ToList();

            IQueryable<SysMenu> ISysMenu = menuService.LoadEntites(e => e.IsActive == 0);
            IQueryable<SysMenu> _ISysMenu = ISysMenu.Where(e => e.PMenuID == Guid.Empty).OrderBy(e=>e.Sort);
            builder.Append("[");
            GetNode(ISysMenu, _ISysMenu);
            builder.Append("]");
            return Json(builder.ToString(), JsonRequestBehavior.AllowGet);
        }
        StringBuilder builder = new StringBuilder();
        public void GetNode(IQueryable<SysMenu> ISysMenu, IQueryable<SysMenu> _isysMenu)
        {
            foreach (SysMenu item in _isysMenu)
            {
                builder.Append("{");
                builder.Append("id:'");
                builder.Append(item.MenuID);
                builder.Append("',");
                builder.Append("text:'");
                builder.Append(item.MenuName);
                builder.Append("'");

                if (menulist.Count != 0)
                {
                    if (menulist.Contains(item.MenuID))
                    {
                        builder.Append(",");
                        builder.Append("state:{");
                        builder.Append("checked:true");
                        builder.Append("}");
                    }
                }

                IQueryable<SysMenu> _sysmenu = ISysMenu.Where(e => e.PMenuID == item.MenuID).OrderBy(e => e.Sort);
                if (_sysmenu.Count() > 0)
                {
                    builder.Append(",");
                    builder.Append("nodes:[");
                    GetNode(ISysMenu, _sysmenu);
                    builder.Append("]");
                }
                builder.Append("},");

            }
            builder = builder.Remove(builder.Length - 1, 1);

        }
    }
}
